package com.wcs.exam.controller.biz;

import cn.hutool.core.util.ObjectUtil;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.server.upload.Upload;
import com.wcs.exam.common.server.upload.UploadService;
import com.wcs.exam.common.util.DocUtil;
import com.wcs.exam.common.util.FileUtils;
import com.wcs.exam.controller.biz.resp.UploadDocResp;
import com.wcs.exam.controller.biz.resp.UploadPicResp;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传接口
 *
 * @author wcs
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UploadCommonBiz {

    @NotNull
    private final UploadService uploadService;

    @NotNull
    private final SysConfigCommonBiz sysConfigCommonBiz;

    public Result<UploadPicResp> uploadPic(MultipartFile picFile) {
        if (!FileUtils.isPic(picFile)) {
            return Result.error("目前只支持：{}，请选择图片上传".replace("{}", FileUtils.PIC_TYPE_MAP));
        }

        Upload upload = sysConfigCommonBiz.getSysConfig(Upload.class);
        if (ObjectUtil.isEmpty(upload) || ObjectUtil.isEmpty(upload.getStoragePlatform())) {
            return Result.error("上传参数没配置");
        }

        String fileUrl = uploadService.uploadPic(picFile, upload);
        return Result.success(new UploadPicResp(upload.getStoragePlatform(), fileUrl));
    }

    public Result<UploadDocResp> upload(MultipartFile file, Boolean isPublicRead) {
        if (!isPublicRead && !FileUtils.isDoc(file)) {
            return Result.error("目前只支持：{}，请选择文件上传".replace("{}", FileUtils.DOC_TYPE_MAP));
        }
        if (isPublicRead && !FileUtils.isApp(file)) {
            return Result.error("目前只支持：{}，请选择文件上传".replace("{}", FileUtils.APP_TYPE_MAP));
        }

        UploadDocResp resp = new UploadDocResp();
        Upload upload = sysConfigCommonBiz.getSysConfig(Upload.class);
        resp.setStoragePlatform(upload.getStoragePlatform());
        if (ObjectUtil.isEmpty(upload) || ObjectUtil.isEmpty(upload.getStoragePlatform())) {
            return Result.error("上传参数没配置");
        }

        resp.setDocUrl(uploadService.uploadDoc(file, upload, isPublicRead));
        try {
            resp.setPageCount(DocUtil.getDocPageCount(file.getOriginalFilename(), file.getInputStream()));
            return Result.success(resp);
        } catch (Exception e) {
            log.error("文档错误", e);
            return Result.error("文档错误");
        }
    }

}
